package com.b2c.erp.kuaidi100;

import com.alibaba.fastjson.JSONObject;
import com.b2c.common.third.express.KuaiDi100ExpressClient;
import com.b2c.common.utils.HttpUtil;
import com.b2c.common.utils.Md5Util;
import com.b2c.entity.erp.vo.PrintImgVo;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import org.springframework.util.StringUtils;

import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：
 * 快递面单打印
 *
 * @author qlp
 * @date 2019-09-17 20:19
 */
public class ExpressPrintUtils {

    /**
     * 云打印生成图片
     *
     * @param print
     * @param openSubscription 是否开启订阅功能，默认是：0（不开启），如果是1说明开启订阅功能此时pollCallBackUrl必须填入
     * @param
     */
    public static ResultVo<ExpressPrintResult> generateExpressPrintImg(PrintImgVo print, int openSubscription,String partnerId,String partnerKey) {
        if (StringUtils.isEmpty(print.getSendManMobile()) || StringUtils.isEmpty(print.getSendManName()) || StringUtils.isEmpty(print.getSendManPrintAddr())) {
            new ResultVo<>(EnumResultVo.ParamsError, "寄件人地址不能为空 ");//寄件人地址不能为空
        }
        if (StringUtils.isEmpty(print.getRecManName()) || StringUtils.isEmpty(print.getRecManMobile()) || StringUtils.isEmpty(print.getRecManPrintAddr())) {
            new ResultVo<>(EnumResultVo.ParamsError, "收件人地址不能为空 ");
        }
        if (openSubscription == 1 && StringUtils.isEmpty(print.getPollCallBackUrl()))
            new ResultVo<>(EnumResultVo.ParamsError, "回调地址不能为空 ");


        try {
            Map<String, String> params = new HashMap<>();
            //params.put("method", "getPrintImg");
            params.put("key", "HemHbdOY1667");
            String now = String.valueOf(System.currentTimeMillis());
            params.put("t", now);

            JSONObject param = new JSONObject();
            param.put("type", "10");
            param.put("partnerId", "4398900340329");//电子面单客户账户或月结账号
//            param.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHRTFqeUkyaktxbHhNdzFVcnhXY2dXT0dYRkFyWG54ZThNU1JIUzIzWEN4aw==");
            param.put("partnerKey", "dFVsaGlNYW1LdU0yMkx1bHR5OVJHTFJDMjdPeThSLyt1ckVNMHNDMnFjaW1VdC9Rd3doNE5wYVVsSTVHTWpqaw==");

            //收件人
            param.put("recManName", print.getRecManName());
            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0-9]))\\d{8}$";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(print.getRecManMobile());
            boolean isMatch = m.matches();
            if (isMatch) {
                System.out.println("[ExpressPrintUtils]您的手机号" + print.getRecManMobile() + "是正确格式@——@");
                param.put("recManMobile", print.getRecManMobile());
            } else {
                System.out.println("[ExpressPrintUtils]您的手机号" +  print.getRecManMobile() + "是错误格式！！！");
                param.put("recManTel", print.getRecManMobile());
            }
/*            param.put("recManProvince",print.getRecManProvince());
            param.put("recManCity",print.getRecManCity());
            param.put("recManDistrict",print.getRecManDistrict());
            param.put("recManAddr",print.getRecManAddr());*/
            param.put("recManPrintAddr", print.getRecManPrintAddr());

            //发件人
            param.put("sendManName", print.getSendManName());
//            param.put("sendManMobile", print.getSendManMobile());
            param.put("sendManTel", print.getSendManMobile());
//            param.put("sendManProvince", sendManAddress.getProvinceName());
//            param.put("sendManCity", sendManAddress.getCityName());
//            param.put("sendManDistrict", sendManAddress.getDistrictName());
//            param.put("sendManAddr", sendManAddress.getAddress());
            param.put("sendManPrintAddr", print.getSendManPrintAddr());

            //快递信息
            param.put("orderId", print.getOrderId());//订单编号
            param.put("cargo", print.getCargo());
            param.put("count", print.getCount());
            param.put("weight", print.getWeight());
            param.put("volumn", print.getVolumn());
//            param.put("tempid", "5ada972099e8483faef7b33113a0dc6f");//面单id
            param.put("tempid", "3e56656a1f164002939306ec845c1391");//面单id
            param.put("kuaidicom", print.getKuaidicom());//快递公司
            param.put("net", print.getNet());
            param.put("needChild", "0");
            param.put("needBack", "0");

//            param.put("height","180");//快递面单的高
//            param.put("width","100");//快递面单的宽

            param.put("op", String.valueOf(openSubscription));//是否开启订阅功能，默认是：0（不开启），如果是1说明开启订阅功能此时pollCallBackUrl必须填入
            if (openSubscription == 1)
                param.put("pollCallBackUrl", print.getPollCallBackUrl() + "/notify/express_notify");
            param.put("resultv2", "0");


            StringBuilder builder = new StringBuilder(param.toJSONString());
            builder.append(now);
            builder.append("HemHbdOY1667");
            builder.append("beb93369e66d4c3f8ecfb8074a9bb9a6");
            params.put("sign", Md5Util.MD5(builder.toString()));

            StringBuilder builder_1 = new StringBuilder("&param=" + param.toJSONString());
            builder_1.append("&" + HttpUtil.map2Url(params));

            HttpResponse<String> response = KuaiDi100ExpressClient.doPost("http://poll.kuaidi100.com/printapi/printtask.do?method=getPrintImg", builder_1.toString());
            //{"result":true,"returnCode":"200","message":"提交成功","data":{"taskId":"****",//任务ID"kuaidicom":"****",//快递公司编码"kuaidinum":"****",//快递单号"imgBase64":"****"//面单BASE64编码图片}}
            if (response.statusCode() == 200) {
                //log.info("请求打印快递单返回信息："+response.body());
                JSONObject obj = JSONObject.parseObject(response.body());
                if (obj.getBoolean("result") == false) {
//                    if(obj.getString("status").equals("500")){
//                        //授权过期，重新授权
//                        //https://poll.kuaidi100.com/printapi/authThird.do
//
//                    }
                    return new ResultVo<>(EnumResultVo.Fail, obj.getString("message"));
                }

                if (obj.getInteger("returnCode") == 200) {
                    //添加快递打印图片
                    String str = obj.getString("data").replace("[\\\"", "");
                    String str_1 = str.replace("\\\"]", "");
                    String str_2 = str_1.replace("\\\\n", "");
                    JSONObject dataObj = JSONObject.parseObject(str_2);

                    ExpressPrintResult printResult = new ExpressPrintResult();
                    printResult.setImgBase64(dataObj.getString("imgBase64"));
                    printResult.setKuaidicom(dataObj.getString("kuaidicom"));
                    printResult.setKuaidicomName(print.getKuaidicomname());
                    printResult.setKuaidinum(dataObj.getString("kuaidinum"));
                    return new ResultVo<>(EnumResultVo.SUCCESS, printResult);
//                    String addSendExpress = "INSERT INTO order_send_express set order_num=?,send_company_code=?,send_code=?,send_print_img=?,create_on=unix_timestamp(now())";
//                    jdbcTemplate.update(addSendExpress, print.getOrderId(), dataObj.getString("kuaidicom"), dataObj.getString("kuaidinum"), dataObj.getString("imgBase64"));
//                    //更新出货信息
//                    String updErpInvoice = "UPDATE " + Tables.Order + " SET send_company=?,send_company_code=?,send_code=?,send_time=unix_timestamp(now()),send_status=3 WHERE order_num=? ";
//                    jdbcTemplate.update(updErpInvoice, "韵达快递", dataObj.getString("kuaidicom"), dataObj.getString("kuaidinum"), print.getOrderId());
//                    return dataObj.getString("imgBase64");
                } else return new ResultVo<>(EnumResultVo.Fail, response.body());
            } else return new ResultVo<>(EnumResultVo.Fail, response.body());
        } catch (Exception e) {
//            log.error("请求打印快递单异常：" + e);
            return new ResultVo<>(EnumResultVo.SystemException);
        }

    }
}
